<template>
  <div class="admin-order-page">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <div class="admin-logo">
          <div class="admin-logo-icon">管</div>
          <div class="admin-logo-text">管理系统</div>
        </div>
      </div>
      
      <div class="sidebar-menu">
        <div 
          v-for="menu in menuList" 
          :key="menu.name"
          class="menu-item"
          :class="{ active: menu.name === 'order' }"
          @click="handleMenuClick(menu)"
        >
          <div class="menu-icon">{{ menu.icon }}</div>
          <span>{{ menu.label }}</span>
        </div>
      </div>
      
      <div class="sidebar-footer">
        <div class="admin-avatar-container">
          <div class="admin-avatar">{{ adminInitial }}</div>
          <div class="admin-info">
            <div class="admin-name">{{ adminName }}</div>
            <div class="admin-role">超级管理员</div>
          </div>
        </div>
        
        <!-- 退出登录按钮 -->
        <div class="logout-btn" @click="handleLogout">
          <div class="logout-icon">🚪</div>
          <span>退出登录</span>
        </div>
      </div>
    </div>
    
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 顶部导航 -->
      <div class="top-nav">
        <h1 class="page-title">
          <div class="page-title-icon">📦</div>
          订单管理
        </h1>
      </div>

      <!-- 主内容 -->
      <div class="content-wrapper">
        <el-card class="content-card">
          <!-- 搜索筛选区域 -->
          <el-card class="filter-card">
            <el-form :inline="true" :model="filterForm" class="filter-form">
              <el-form-item label="订单号">
                <el-input
                  v-model="filterForm.orderNo"
                  placeholder="请输入订单号"
                  clearable
                  style="width: 200px"
                  @keyup.enter="handleSearch"
                />
              </el-form-item>
              <el-form-item label="支付状态">
                <el-select
                  v-model="filterForm.paymentStatus"
                  placeholder="请选择支付状态"
                  clearable
                  style="width: 150px"
                >
                  <el-option label="未支付" :value="0" />
                  <el-option label="已支付" :value="1" />
                </el-select>
              </el-form-item>
              <el-form-item label="订单状态">
                <el-select
                  v-model="filterForm.orderStatus"
                  placeholder="请选择订单状态"
                  clearable
                  style="width: 150px"
                >
                  <el-option label="待支付" :value="0" />
                  <el-option label="待发货" :value="1" />
                  <el-option label="配送中" :value="2" />
                  <el-option label="待取件" :value="3" />
                  <el-option label="已完成" :value="4" />
                  <el-option label="已取消" :value="5" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 订单列表 -->
          <el-table
            v-loading="loading"
            :data="orderList"
            stripe
            style="width: 100%; margin-top: 20px;"
            :fit="true"
          >
            <el-table-column prop="orderNo" label="订单号" min-width="180" />
            <el-table-column label="订单商品" min-width="300">
              <template #default="{ row }">
                <div class="order-items">
                  <div 
                    v-for="item in row.orderItems.slice(0, 2)" 
                    :key="item.productId"
                    class="order-item"
                  >
                    <img :src="item.productImage" class="product-image" />
                    <div class="product-info">
                      <div class="product-name">{{ item.productName }}</div>
                      <div class="product-price">¥{{ item.unitPrice }} × {{ item.quantity }}</div>
                    </div>
                  </div>
                  <div v-if="row.orderItems.length > 2" class="more-items">
                    等{{ row.orderItems.length }}件商品
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="订单金额" width="120">
              <template #default="{ row }">
                <div class="order-amount">¥{{ row.actualAmount }}</div>
              </template>
            </el-table-column>
            <el-table-column label="支付状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.paymentStatus === 1 ? 'success' : 'warning'">
                  {{ row.paymentStatus === 1 ? '已支付' : '未支付' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="订单状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getOrderStatusType(row.orderStatus)">
                  {{ getOrderStatusText(row.orderStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="180" fixed="right" align="center">
              <template #default="{ row }">
                <el-button type="text" size="small" @click="handleViewDetail(row)">
                  查看详情
                </el-button>
                <el-button 
                  v-if="row.paymentStatus === 1 && row.orderStatus < 4"
                  type="text" 
                  size="small" 
                  @click="handleUpdateStatus(row)"
                >
                  更新状态
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 20px; justify-content: flex-end;"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </div>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="currentOrder.paymentStatus === 1 ? 'success' : 'warning'">
              {{ currentOrder.paymentStatus === 1 ? '已支付' : '未支付' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(currentOrder.orderStatus)">
              {{ getOrderStatusText(currentOrder.orderStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ currentOrder.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="实付金额">¥{{ currentOrder.actualAmount }}</el-descriptions-item>
          <el-descriptions-item label="收货人">{{ currentOrder.receiverName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentOrder.receiverPhone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.receiverAddress }}</el-descriptions-item>
          <el-descriptions-item v-if="currentOrder.remark" label="订单备注" :span="2">
            {{ currentOrder.remark }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider>商品清单</el-divider>
        <el-table :data="currentOrder.orderItems" border style="width: 100%">
          <el-table-column label="商品图片" width="100">
            <template #default="{ row }">
              <img :src="row.productImage" class="detail-product-image" />
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">¥{{ row.unitPrice }}</template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="totalPrice" label="小计" width="100">
            <template #default="{ row }">¥{{ row.totalPrice }}</template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="更新订单状态"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="订单号">
          <el-input v-model="statusForm.orderNo" disabled />
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag :type="getOrderStatusType(statusForm.currentStatus)">
            {{ getOrderStatusText(statusForm.currentStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="statusForm.newStatus" placeholder="请选择新状态" style="width: 100%">
            <el-option label="待发货" :value="1" :disabled="statusForm.currentStatus >= 1" />
            <el-option label="配送中" :value="2" :disabled="statusForm.currentStatus >= 2" />
            <el-option label="待取件" :value="3" :disabled="statusForm.currentStatus >= 3" />
            <el-option label="已完成" :value="4" :disabled="statusForm.currentStatus >= 4" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmUpdateStatus">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdminOrderPage, getAdminOrderDetail, updateOrderStatus } from '@/api/order'

const router = useRouter()
const userStore = useUserStore()

// 菜单列表
const menuList = [
  { name: 'dashboard', label: '数据看板', icon: '📊', path: '/admin/dashboard' },
  { name: 'employee', label: '员工管理', icon: '👥', path: '/admin/employee' },
  { name: 'card', label: '福利卡管理', icon: '🎁', path: '/admin/welfare-card' },
  { name: 'product', label: '商品管理', icon: '🛒', path: '/admin/product' },
  { name: 'order', label: '订单管理', icon: '📦', path: '/admin/order' },
  { name: 'statistics', label: '数据统计', icon: '📈', path: '/admin/statistics' }
]

// 管理员信息
const adminName = computed(() => userStore.userInfo?.username || '管理员')
const adminInitial = computed(() => {
  const name = userStore.userInfo?.username || '管'
  return name.charAt(0).toUpperCase()
})

// 筛选表单
const filterForm = ref({
  orderNo: '',
  paymentStatus: null,
  orderStatus: null
})

// 订单列表
const orderList = ref([])
const loading = ref(false)

// 分页
const pagination = ref({
  current: 1,
  size: 20,
  total: 0
})

// 订单详情对话框
const detailDialogVisible = ref(false)
const currentOrder = ref(null)

// 更新状态对话框
const statusDialogVisible = ref(false)
const statusForm = ref({
  orderId: null,
  orderNo: '',
  currentStatus: null,
  newStatus: null
})

// 菜单点击
const handleMenuClick = (menu) => {
  if (menu.path) {
    router.push(menu.path)
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    userStore.resetState()
    router.push('/login')
    ElMessage.success('退出登录成功')
  } catch (error) {
    // 用户取消操作
  }
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '待发货',
    2: '配送中',
    3: '待取件',
    4: '已完成',
    5: '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'primary',
    3: 'success',
    4: 'success',
    5: 'info'
  }
  return typeMap[status] || 'info'
}

// 查询订单列表
const fetchOrderList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.value.current,
      size: pagination.value.size,
      orderNo: filterForm.value.orderNo || undefined,
      paymentStatus: filterForm.value.paymentStatus,
      orderStatus: filterForm.value.orderStatus
    }
    const res = await getAdminOrderPage(params)
    if (res.code === 200) {
      orderList.value = res.data.records
      pagination.value.total = res.data.total
    } else {
      ElMessage.error(res.message || '查询订单列表失败')
    }
  } catch (error) {
    console.error('查询订单列表失败:', error)
    ElMessage.error('查询订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchOrderList()
}

// 重置
const handleReset = () => {
  filterForm.value = {
    orderNo: '',
    paymentStatus: null,
    orderStatus: null
  }
  pagination.value.current = 1
  fetchOrderList()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.value.size = val
  pagination.value.current = 1
  fetchOrderList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.value.current = val
  fetchOrderList()
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const res = await getAdminOrderDetail(row.id)
    if (res.code === 200) {
      currentOrder.value = res.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(res.message || '查询订单详情失败')
    }
  } catch (error) {
    console.error('查询订单详情失败:', error)
    ElMessage.error('查询订单详情失败')
  }
}

// 更新状态
const handleUpdateStatus = (row) => {
  statusForm.value = {
    orderId: row.id,
    orderNo: row.orderNo,
    currentStatus: row.orderStatus,
    newStatus: null
  }
  statusDialogVisible.value = true
}

// 确认更新状态
const handleConfirmUpdateStatus = async () => {
  if (statusForm.value.newStatus === null) {
    ElMessage.warning('请选择新状态')
    return
  }
  if (statusForm.value.newStatus <= statusForm.value.currentStatus) {
    ElMessage.warning('新状态必须大于当前状态')
    return
  }
  
  try {
    const res = await updateOrderStatus(statusForm.value.orderId, statusForm.value.newStatus)
    if (res.code === 200) {
      ElMessage.success('更新订单状态成功')
      statusDialogVisible.value = false
      fetchOrderList()
    } else {
      ElMessage.error(res.message || '更新订单状态失败')
    }
  } catch (error) {
    console.error('更新订单状态失败:', error)
    ElMessage.error('更新订单状态失败')
  }
}

// 初始化
onMounted(() => {
  fetchOrderList()
})
</script>

<style scoped lang="scss">
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.admin-order-page {
  display: flex;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 侧边栏样式 */
.sidebar {
  width: 220px;
  background-color: white;
  height: 100vh;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.admin-logo {
  display: flex;
  align-items: center;
}

.admin-logo-icon {
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  box-shadow: 0 2px 8px rgba(255, 112, 67, 0.3);
}

.admin-logo-text {
  font-size: 18px;
  font-weight: 600;
  color: #ff5722;
}

.sidebar-menu {
  flex: 1;
  padding: 20px 0;
  overflow-y: auto;
}

.menu-item {
  padding: 12px 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
  
  &:hover {
    background-color: #f5f7fa;
  }
  
  &.active {
    background: linear-gradient(90deg, rgba(255, 112, 67, 0.08) 0%, rgba(255, 112, 67, 0.15) 100%);
    color: #ff5722;
    border-right: 3px solid #ff5722;
  }
}

.menu-icon {
  margin-right: 10px;
  width: 20px;
  text-align: center;
}

.sidebar-footer {
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.admin-avatar-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.admin-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-weight: bold;
  margin-right: 10px;
  box-shadow: 0 2px 6px rgba(255, 112, 67, 0.3);
}

.admin-info {
  flex: 1;
}

.admin-name {
  font-weight: 500;
  font-size: 14px;
}

.admin-role {
  color: #909399;
  font-size: 12px;
}

/* 退出登录按钮 */
.logout-btn {
  width: 100%;
  background: linear-gradient(135deg, #ef5350 0%, #e53935 100%);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(239, 83, 80, 0.3);
}

.logout-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(239, 83, 80, 0.4);
}

.logout-icon {
  font-size: 14px;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  margin-left: 220px;
  padding: 20px;
}

/* 顶部导航 */
.top-nav {
  background-color: white;
  border-radius: 12px;
  padding: 15px 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  display: flex;
  align-items: center;
  margin: 0;
}

.page-title-icon {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  color: white;
  box-shadow: 0 2px 8px rgba(255, 112, 67, 0.3);
}

.content-wrapper {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow-x: auto;
}

.content-card {
  border: none;
  box-shadow: none;
  
  :deep(.el-card__body) {
    padding: 0;
  }
}

.filter-card {
  margin-bottom: 20px;
  background: #fafafa;
  border-radius: 8px;
}

.filter-form {
  margin-bottom: 0;
}

/* 订单列表样式 */
.order-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.order-item {
  display: flex;
  gap: 10px;
  align-items: center;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.product-price {
  font-size: 12px;
  color: #999;
}

.more-items {
  font-size: 12px;
  color: #999;
  text-align: center;
}

.order-amount {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}

/* 订单详情样式 */
.order-detail {
  padding: 20px 0;
}

.detail-product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

/* Element Plus 组件样式优化 */
:deep(.el-descriptions__label) {
  font-weight: bold;
  color: #ff5722;
}

:deep(.el-table) {
  margin-top: 20px;
  width: 100% !important;
  
  .el-table__header-wrapper,
  .el-table__body-wrapper {
    width: 100% !important;
  }
  
  .el-table__header th {
    background-color: #fff5f2;
    color: #ff5722;
    font-weight: 600;
  }
  
  .el-table__row:hover {
    background-color: #fff9f7;
  }
  
  // 确保表格自适应容器宽度
  table {
    width: 100% !important;
  }
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 12px;
  padding: 0 10px;
  font-weight: 500;
  
  &.el-tag--success {
    background: linear-gradient(135deg, #66bb6a 0%, #43a047 100%);
    border: none;
    color: white;
  }
  
  &.el-tag--info {
    background: linear-gradient(135deg, #bdbdbd 0%, #9e9e9e 100%);
    border: none;
    color: white;
  }
  
  &.el-tag--warning {
    background: linear-gradient(135deg, #ffa726 0%, #fb8c00 100%);
    border: none;
    color: white;
  }
  
  &.el-tag--primary {
    background: linear-gradient(135deg, #42a5f5 0%, #1e88e5 100%);
    border: none;
    color: white;
  }
}

/* 对话框优化 */
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  
  .el-dialog__header {
    background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
    padding: 20px;
    
    .el-dialog__title {
      color: white;
      font-weight: 600;
      font-size: 18px;
    }
    
    .el-dialog__headerbtn .el-dialog__close {
      color: white;
      font-size: 20px;
      
      &:hover {
        color: #fff;
      }
    }
  }
  
  .el-dialog__body {
    padding: 25px 30px;
  }
}

/* 表单优化 */
:deep(.el-form) {
  .el-form-item__label {
    color: #ff5722;
    font-weight: 600;
    font-size: 14px;
  }
  
  .el-input__wrapper {
    border-radius: 8px;
    padding: 8px 15px;
    transition: all 0.3s ease;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
    
    &:hover {
      box-shadow: 0 2px 6px rgba(255, 112, 67, 0.15);
    }
    
    &.is-focus {
      box-shadow: 0 0 0 2px rgba(255, 112, 67, 0.2);
    }
  }
  
  .el-select {
    .el-input__wrapper {
      border-radius: 8px;
      padding: 8px 15px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
      
      &:hover {
        box-shadow: 0 2px 6px rgba(255, 112, 67, 0.15);
      }
      
      &.is-focus {
        box-shadow: 0 0 0 2px rgba(255, 112, 67, 0.2);
      }
    }
  }
}

/* 分页优化 */
:deep(.el-pagination) {
  .el-pager li.is-active {
    background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
    color: white;
  }
  
  .el-pager li:hover {
    color: #ff5722;
  }
  
  button:hover {
    color: #ff5722;
  }
}

/* 按钮优化 */
:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  
  &.el-button--primary {
    background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
    border: none;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    }
  }
  
  &.el-button--text {
    color: #409EFF;
    
    &:hover {
      color: #66b1ff;
    }
  }
}
</style>

